
import _ from "lodash";
import Vue from "vue";
const isFunction = f => typeof f === "function";

let initData = {
    el: null,
    binding: null,
    vm: null
};

const getOptions = (keys=[],el,vm) => {
    let optionsList = [];
    optionsList = keys.map(key => {
        let keyName = `table-scroll-${key}`;
        let value = el.getAttribute(keyName);
        if(value === null) {
            value = _.get(vm, `data.attrs.${keyName}`);
        }
        return value;
    });
    return optionsList;
};

let handleScroll = _.throttle(async function() {
    let {el, binding, vm} = initData;
    let loadMore = _.get(binding, 'value');
    if(!loadMore || !isFunction(loadMore)) {
        return;
    }
    let [
        disabled,
        loadDistance,
    ] = getOptions(
        [
            'disabled',
            'loadDistance',
        ],
        el,
        vm);

    let sign = Number(loadDistance) || 100;

    const bottomLeftDistance = this.scrollHeight - this.scrollTop - this.clientHeight;
    if (bottomLeftDistance <= sign) {

        if(disabled) {
            return;
        }
        loadMore();
    }
}, 200);

const tableScroll = (el, binding, vm) => {
    initData.el = el;
    initData.binding = binding;
    initData.vm = vm;
    const selectWrap = el.querySelector('.el-table__body-wrapper');
    selectWrap && selectWrap.addEventListener('scroll', handleScroll);
};

Vue.directive('tableScroll', {
    bind: (el, binding,vm) => tableScroll(el, binding,vm),
    update: (el, binding,vm) => tableScroll(el, binding,vm),
    unbind: (el, binding) => {
        const selectWrap = el.querySelector('.el-table__body-wrapper');
        selectWrap && selectWrap.removeEventListener('scroll', tableScroll);
    },
});
